package com.tbl.modules.wms.controller.stock;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.constant.EbsInterfaceEnum;
import com.tbl.modules.wms.dao.webservice.FewmDAO;
import com.tbl.modules.wms.entity.baseinfo.Shelf;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.inventory.Inventory;
import com.tbl.modules.wms.entity.inventory.InventoryRegistration;
import com.tbl.modules.wms.entity.split.Split;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.baseinfo.ShelfService;
import com.tbl.modules.wms.service.businessutils.BusinessUtilsService;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.interfacelog.InterfaceDoService;
import com.tbl.modules.wms.service.inventory.InventoryRegistrationService;
import com.tbl.modules.wms.service.inventory.InventoryService;
import com.tbl.modules.wms.service.pda.SplitService;
import com.tbl.modules.wms.service.storageinfo.StorageInfoService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 盘点审核
 * @author 70486
 */
@Controller
@RequestMapping(value = "/inventoryReview")
public class InventoryReviewController extends AbstractController {

    /**
     * 盘点登记服务类
     */
    @Autowired
    private InventoryRegistrationService inventoryRegistrationService;
    /**
     * 角色接口
     */
    @Autowired
    private RoleService roleService;
    /**
     * 盘点审核服务类
     */
	@Autowired
	private InventoryService inventoryService;
    /**
     * wms调用入口
     */
    @Autowired
    private WmsService wmsService;
    /**
     * 库存服务
     */
    @Autowired
    private StorageInfoService storageInfoService;
    /**
     * Webservice服务的接口方法DAO
     */
    @Autowired
    private FewmDAO fewmDAO;
    /**
     * 库位服务
     */
    @Autowired
    private ShelfService shelfService;
    /**
     * 标签初始化表
     */
    @Autowired
    private InstorageDetailService instorageDetailService;
    /**
     * 拆分
     */
    @Autowired
    private SplitService splitService;
    /**
     * 离线接口执行
     */
    @Autowired
    private InterfaceDoService interfaceDoService;
    /**
     * 盘点审核接口一个报文的质保号数量
     */
    @Value("${yddl.inventoryNum}")
    private Integer inventoryNum;
    /**
     * 业务流程公用服务
     */
    @Autowired
    private BusinessUtilsService businessUtilsService;

    /**
     * 跳转到盘点审核列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.inventoryReview));
        List<Map<String,Object>> stateList = new ArrayList<>();
        stateList.add(new HashMap<String,Object>(2) {{
        	put("key","0");
        	put("value","待审核");
        }});
        stateList.add(new HashMap<String,Object>(2) {{
        	put("key","1");
        	put("value","审核中");
        }});
        stateList.add(new HashMap<String,Object>(2) {{
        	put("key","2");
        	put("value","已登记");
        }});
        stateList.add(new HashMap<String,Object>(2) {{
        	put("key","3");
        	put("value","已审核");
        }});
        mv.addObject("stateList",stateList);
        mv.setViewName("techbloom/stock/inventoryReview/inventoryReview_list");
        return mv;
    }

    /**
     * 盘点审核获取列表数据
     * @param queryJsonString
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(2);
        if (!com.alibaba.druid.util.StringUtils.isEmpty(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        String sortName = page.getSortname();
        if (com.alibaba.druid.util.StringUtils.isEmpty(sortName)) {
            sortName = "";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (com.alibaba.druid.util.StringUtils.isEmpty(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        PageUtils pageInventory = inventoryService.getInventoryReviewList(page, map);
        page.setTotalRows(pageInventory.getTotalCount() == 0 ? 1 : pageInventory.getTotalCount());
        map.put("rows", pageInventory.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 弹出到审核页面
     * @param id    ebs盘点单号（一个去杠）
     * @param code  wms盘点单号（多个）
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id, String code) {
        ModelAndView mv = this.getModelAndView();
        List<Inventory> lstInventory = inventoryService.selectList(new EntityWrapper<Inventory>().in("CODE",Arrays.asList(code.split(","))));
        Inventory inventory = lstInventory.get(0);
        mv.setViewName("techbloom/stock/inventoryReview/inventoryReview_edit");
        mv.addObject("id", id);
        mv.addObject("code", code);
        mv.addObject("ebsCode", inventory.getEbsCode());
        if (inventory.getAuditDate() == null){
            Date date = new Date();
            lstInventory.forEach(inv -> {
                inv.setAuditDate(date);
                inventoryService.updateById(inv);
            });
        }
        mv.addObject("auditTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(inventory.getAuditDate()));
        return mv;
    }

    /**
     * 上传审核米数，调拨移库调拨接口（单条盘点审核，接口实时调用）
     * @param qaCode 质保号
     * @param ebsCode ebs盘点单号
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/toExamineSolo.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> toExamineSolo(String qaCode, String ebsCode) {
        Map<String, Object> resultMap = Maps.newHashMap();
        List<Inventory> lstInventory = inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE",ebsCode));

        //一个ebs盘点单下的所有wms盘点单号的主键
        StringBuffer inventoryIdsStringBuffer = new StringBuffer();
        lstInventory.forEach(inventory -> inventoryIdsStringBuffer.append(inventory.getId()));

        //对应ebs盘点单号下的已经盘点的库存(要上传的部分)
        List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                .in("PLAN_ID", inventoryIdsStringBuffer.toString())
                .eq("QACODE", qaCode));
        if (lstInventoryRegistration.size() == 0){
            resultMap.put("result", false);
            resultMap.put("msg", "此线盘尚未盘点，无法审核！");
            return resultMap;
        }
        InventoryRegistration inventoryRegistration = lstInventoryRegistration.get(0);

        StorageInfo storageInfo = storageInfoService.selectOne(new EntityWrapper<StorageInfo>().eq("QACODE", qaCode));
        if (storageInfo == null){
            Split split = splitService.selectOne(new EntityWrapper<Split>().eq("QACODE", qaCode));
            if (split != null){
                storageInfo = new StorageInfo();
                storageInfo.setShelfCode(split.getShelfCode());
                storageInfo.setWarehouseCode(split.getWarehouseCode());
                storageInfo.setFactoryCode(split.getOrg());
                storageInfo.setRfid(split.getRfid());
                storageInfo.setBatchNo(split.getBatchNo());
                storageInfo.setQaCode(split.getQaCode());
            }
        }
        if (storageInfo == null){
            resultMap.put("result", false);
            resultMap.put("msg", "已出库，无需审核！");
            return resultMap;
        }

        //移库接口执行成功与否
        boolean shelfExamineSuccess = true;
        //盘点修改的库位
        Shelf inventoryShelf;

        //库存库位
        List<Shelf> storageInfoShelfCompleteList = shelfService.selectList(new EntityWrapper<Shelf>()
                .eq("CODE",storageInfo.getShelfCode())
                .eq("WAREHOUSECODE",storageInfo.getWarehouseCode())
                .eq("FACTORYCODE",storageInfo.getOrg()));
        if (storageInfoShelfCompleteList.size() == 0){
            resultMap.put("result", false);
            resultMap.put("msg", "库存的库位有误，请核查！");
            return resultMap;
        }
        Shelf storageInfoShelf = storageInfoShelfCompleteList.get(0);

        //如果盘点库位与库存库位不同，那么就要做移库
        if (!inventoryRegistration.getEditshelf().equals(storageInfoShelf.getCodeComplete())){
            //盘点修改的库位
            inventoryShelf = shelfService.selectOne(new EntityWrapper<Shelf>().eq("CODE_COMPLETE", inventoryRegistration.getEditshelf()));
            Map<String, Object> paramsMap = Maps.newHashMap();
            paramsMap.put("RFID", storageInfo.getRfid());
            List<InstorageDetail> instorageDetails = instorageDetailService.selectByMap(paramsMap);
            InstorageDetail instorageDetail = null;
            if (instorageDetails.size()>0){
                instorageDetail = instorageDetails.get(0);
            }

            //调EBS移库调拨接口
            Map<String,Object> paramMap = new HashMap<>(1), inParamMap = new HashMap<>(5);
            inParamMap.put("org",instorageDetail == null ? storageInfo.getOrg() : instorageDetail.getOrg());
            inParamMap.put("batchno", storageInfo.getBatchNo());
            inParamMap.put("qacode", storageInfo.getQaCode());
            //新仓库
            inParamMap.put("inwarehouse", inventoryShelf.getWarehouseCode());
            //新库位
            inParamMap.put("inLocation", inventoryShelf.getCodeComplete());
            paramMap.put("line",inParamMap);
            //实时调用移库调拨接口
            String returnInfo = wmsService.FEWMS008(paramMap, storageInfo.getQaCode(), storageInfo.getBatchNo());
            returnInfo = returnInfo.replace(" ", "");
            //移库接口执行结果
            shelfExamineSuccess = returnInfo.contains("<code>0</code>") || returnInfo.contains("\"code\":0") || returnInfo.contains("S000A000");

            //把移库成功的库存和盘点登记表修改库位
            if (shelfExamineSuccess){
                //更新库存的库位及盘点登记表库位
                storageInfo.setShelfCode(inventoryShelf.getCode());
                storageInfo.setOrg(inventoryShelf.getFactoryCode());
                storageInfo.setWarehouseCode(inventoryShelf.getWarehouseCode());
                storageInfoService.updateById(storageInfo);

                inventoryRegistration.setOrg(inventoryShelf.getFactoryCode());
                inventoryRegistration.setWarehousecode(inventoryShelf.getWarehouseCode());
                inventoryRegistration.setShelfid(inventoryShelf.getCode());
                //修改库位审核成功的执行状态
                inventoryRegistration.setShelfState(1);
            }else {
                inventoryRegistration.setShelfState(0);
            }
            inventoryRegistrationService.updateById(inventoryRegistration);
        }

        //调用米数审核接口（米数审核是必须都要审的）
        Map<String, Object> xmlMap = Maps.newHashMap();
        xmlMap.put("line", new HashMap<String, Object>(4) {{
            put("check_num", ebsCode);
            put("zjdh", inventoryRegistration.getQacode());
            put("qty", inventoryRegistration.getEditmeter());
            put("pandian_by", inventoryRegistration.getUserName());
        }});
        //接口执行失败的质保号
        List<String> failQacodes = wmsService.FEWMS028(xmlMap, inventoryRegistration.getQacode(), inventoryRegistration.getBatchNo());
        //米数审核成功与否
        boolean meterExamineSuccess = failQacodes.size() == 0;

        //把米数审核成功的库存、盘点登记表修改数量
        if (meterExamineSuccess){
            //更新库存米数
            storageInfo.setMeter(inventoryRegistration.getEditmeter());
            storageInfoService.updateById(storageInfo);

            //更新盘点登记表米数
            inventoryRegistration.setMeter(inventoryRegistration.getEditmeter());
            //修改米数审核成功的执行状态
            inventoryRegistration.setState(1L);
        }else {
            inventoryRegistration.setState(0L);
        }
        inventoryRegistrationService.updateById(inventoryRegistration);

        if (shelfExamineSuccess && meterExamineSuccess){
            resultMap.put("result", true);
            resultMap.put("msg", "审核成功！");
        }else{
            if (!shelfExamineSuccess && !meterExamineSuccess){
                resultMap.put("result", false);
                resultMap.put("msg", "同步米数失败！移库失败！");
            }else if (!shelfExamineSuccess){
                resultMap.put("result", false);
                resultMap.put("msg", "移库失败！");
            }else {
                resultMap.put("result", false);
                resultMap.put("msg", "同步米数失败！");
            }
        }

        //更新计划单状态为已审核/审核中
        lstInventory.forEach(inventory -> {
            String statessArray = inventoryRegistrationService.selectExamineArray(inventory.getId().intValue());
            inventoryRegistrationService.updateExamStatus(inventory.getId().intValue(), StringUtils.isBlank(statessArray) ? 0 : statessArray.contains("0")
                    || statessArray.contains("3") ? 2L : 3L);
        });

        return resultMap;
    }

    /**
     * 上传审核米数，调移库调拨接口（批量盘点审核，接口离线调用）
     * @param ebsCode ebs盘点单号
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/toExamineBatch.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> toExamineBatch(String ebsCode) {
        List<Inventory> lstInventory = inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE",ebsCode));

        //一个ebs盘点单下的所有wms盘点单号的主键
        StringBuffer inventoryIdsStringBuffer = new StringBuffer();
        lstInventory.forEach(inventory -> inventoryIdsStringBuffer.append(inventory.getId()));

        //所有的对应ebs盘点单号下的已经盘点的库存(要上传的部分并且是数量没有差异的，有差异的数量需要单个审核)
        List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                .in("PLAN_ID", inventoryIdsStringBuffer.toString())
                .in("STATE", "0,3")
                .in("RESULT","1,4"));
        if (lstInventoryRegistration.size()>0){
            //调用盘点审核接口，把米数同步至ebs，
            IdentityHashMap xmlMap = Maps.newIdentityHashMap();
            Map<String, Object> paramMap;
            int i = 0;
            boolean divisibility = false;
            List<Long> inventoryRegistrationIds = new LinkedList<>();
            List<StorageInfo> lstMoveShelfStorageInfo = new LinkedList<>();
            for (InventoryRegistration inventoryRegistration : lstInventoryRegistration){
                inventoryRegistrationIds.add(inventoryRegistration.getId());
                i++;
                paramMap = Maps.newHashMap();
                paramMap.put("check_num", ebsCode);
                paramMap.put("zjdh", inventoryRegistration.getQacode());
                paramMap.put("qty", inventoryRegistration.getEditmeter());
                paramMap.put("pandian_by", inventoryRegistration.getUserName());
                xmlMap.put(new String("line"), paramMap);

                divisibility = false;

                if (i == inventoryNum || (i % inventoryNum == 0 & i > inventoryNum )){
                    divisibility = true;
                    logger.info("##################FEWMS028存入离线接口表#######数量："+i+"################");
                    Long exmineId = fewmDAO.selectSeqPrintInfo();
                    JSONArray jArray = new JSONArray();
                    jArray.add(xmlMap);
                    String str = jArray.toString();
                    interfaceDoService.insertDo(EbsInterfaceEnum.FEWMS028, "EBS接口-盘点米数审核", str, DateUtils.getTime(),
                            "", "", exmineId, ebsCode);
                    //更新盘点登记表上传离线接口表集结号
                    InventoryRegistration inventoryRegistrationEntity = new InventoryRegistration();
                    inventoryRegistrationEntity.setExamined(exmineId);
                    inventoryRegistrationService.update(inventoryRegistrationEntity, new EntityWrapper<InventoryRegistration>()
                            .in("ID",inventoryRegistrationIds));

                    inventoryRegistrationIds = new LinkedList<>();
                    xmlMap = new IdentityHashMap<>();
                }

                if (inventoryRegistration.getShelfState()!=1 && inventoryRegistration.getShelfState()!=2) {
                    StorageInfo storageInfo = null;
                    List<StorageInfo> lstStorageInfo = storageInfoService.selectList(new EntityWrapper<StorageInfo>()
                            .eq("RFID", inventoryRegistration.getRfid()));
                    if (lstStorageInfo.size() == 0) {
                        List<Split> lstSplit = splitService.selectList(new EntityWrapper<Split>().eq("QACODE", inventoryRegistration.getQacode()));
                        if (lstSplit.size() > 0) {
                            Split split = lstSplit.get(0);
                            storageInfo = new StorageInfo();
                            storageInfo.setShelfCode(split.getShelfCode());
                            storageInfo.setWarehouseCode(split.getWarehouseCode());
                            storageInfo.setFactoryCode(split.getOrg());
                            storageInfo.setRfid(split.getRfid());
                            storageInfo.setBatchNo(split.getBatchNo());
                            storageInfo.setQaCode(split.getQaCode());
                        }
                    } else {
                        storageInfo = lstStorageInfo.get(0);
                    }
                    if (storageInfo != null) {
                        List<Shelf> storageInfoShelfCompleteList = shelfService.selectList(new EntityWrapper<Shelf>()
                                .eq("CODE", storageInfo.getShelfCode())
                                .eq("WAREHOUSECODE", storageInfo.getWarehouseCode())
                                .eq("FACTORYCODE", storageInfo.getOrg()));
                        if (storageInfoShelfCompleteList.size() > 0) {
                            //库存库位
                            Shelf storageInfoShelf = storageInfoShelfCompleteList.get(0);
                            //调用移库调拨接口:如果库存的库位与盘点的库位不相同，才能执行移库接口
                            if (StringUtils.isNotBlank(inventoryRegistration.getEditshelf()) &&
                                    !inventoryRegistration.getEditshelf().equals(storageInfoShelf.getCodeComplete())) {
                                //盘点修改的库位
                                Shelf inventoryShelf = shelfService.selectOne(new EntityWrapper<Shelf>()
                                        .eq("CODE_COMPLETE", inventoryRegistration.getEditshelf()));

                                //添加要修改库位的库存
                                storageInfo.setOrg(inventoryShelf.getFactoryCode());
                                storageInfo.setWarehouseCode(inventoryShelf.getWarehouseCode());
                                storageInfo.setShelfCode(inventoryShelf.getCode());
                                lstMoveShelfStorageInfo.add(storageInfo);

                                Map<String, Object> rfidMap = Maps.newHashMap();
                                rfidMap.put("RFID", storageInfo.getRfid());
                                List<InstorageDetail> lstInstorageDetail = instorageDetailService.selectByMap(rfidMap);
                                InstorageDetail instorageDetail = null;
                                if (lstInstorageDetail.size() > 0) {
                                    instorageDetail = lstInstorageDetail.get(0);
                                }

                                //调EBS移库调拨接口
                                Map<String, Object> paramsMap = new HashMap<>(1), inParamMap = new HashMap<>(5);
                                inParamMap.put("org", instorageDetail == null ? storageInfo.getOrg() : instorageDetail.getOrg());
                                inParamMap.put("batchno", storageInfo.getBatchNo());
                                inParamMap.put("qacode", storageInfo.getQaCode());
                                //新仓库
                                inParamMap.put("inwarehouse", inventoryShelf.getWarehouseCode());
                                //新库位
                                inParamMap.put("inLocation", inventoryShelf.getCodeComplete());
                                paramsMap.put("line", inParamMap);
                                logger.info("FEWMS008存入接口待执行表！");
                                interfaceDoService.insertDo(EbsInterfaceEnum.FEWMS008, "EBS接口-调拨、移库接口", JSONObject.toJSONString(paramsMap),
                                        DateUtils.getTime(), inventoryRegistration.getQacode(), inventoryRegistration.getBatchNo(), 3L, ebsCode);
                            }
                        }
                    }
                }
            }

            //批量修改库存库位，拆分表库位，盘点登记表库位
            if (lstMoveShelfStorageInfo.size()>0){
                storageInfoService.updateBatchById(lstMoveShelfStorageInfo);
                splitService.updateBatch(lstMoveShelfStorageInfo);
                inventoryRegistrationService.updateShelfByInventory(lstMoveShelfStorageInfo);
            }

            if (!divisibility){
                logger.info("##################FEWMS028存入离线接口表#######数量："+i+"################");
                Long exmineId = fewmDAO.selectSeqPrintInfo();

                JSONArray jArray = new JSONArray();
                jArray.add(xmlMap);
                String str = jArray.toString();

                interfaceDoService.insertDo(EbsInterfaceEnum.FEWMS028,"EBS接口-盘点米数审核",str,DateUtils.getTime(),"","", exmineId,ebsCode);
                //更新盘点登记表上传离线接口表集结号
                InventoryRegistration inventoryRegistrationEntity = new InventoryRegistration();
                inventoryRegistrationEntity.setExamined(exmineId);
                inventoryRegistrationService.update(inventoryRegistrationEntity,new EntityWrapper<InventoryRegistration>().in("ID",inventoryRegistrationIds));
            }

            //更新计划单状态为已审核/审核中
            lstInventory.forEach(inventory -> {
                String statessArray = inventoryRegistrationService.selectExamineArray(inventory.getId().intValue());
                inventoryRegistrationService.updateExamStatus(inventory.getId().intValue(), StringUtils.isBlank(statessArray) ? 0 : statessArray.contains("0")
                        || statessArray.contains("3") ? 2L : 3L);
            });
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        businessUtilsService.inventoryMeterBusiness();

        return new HashMap<String,Object>(2) {{
            put("result",true);
            put("msg","提交审核成功，请耐心等待执行结果！");
        }};
    }

    /**
     * 盘点审核修改盘点输入栏米数（如果是已经审核成功状态的，一律无能编辑）
     * @param qaCode 质保号
     * @param amount 数量
     * @param ebsCode EBS盘点单号
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/updateAmount")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateAmount(String qaCode, String amount, String ebsCode) {
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            StringBuffer inventoryIdbuffer = new StringBuffer();
            inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE", ebsCode)).forEach(inventory -> inventoryIdbuffer.append(inventory.getId()).append(","));
            List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                    .eq("QACODE", qaCode)
                    .in("PLAN_ID", inventoryIdbuffer.toString().split(",")));
            if (lstInventoryRegistration.size()>0){
                InventoryRegistration inventoryRegistration = lstInventoryRegistration.get(0);
                //如果是米数审核状态已经成功了，那么无需修改盘点米数了
                if (inventoryRegistration.getState() == 1){
                    resultMap.put("result", false);
                    resultMap.put("msg", "盘点已审核，无需修改！");
                }else {
                    inventoryRegistration.setEditmeter(amount);
                    inventoryRegistrationService.updateById(inventoryRegistration);
                    resultMap.put("result", true);
                    resultMap.put("msg", "更新成功！");
                }
            }else {
                resultMap.put("result", false);
                resultMap.put("msg", "此线盘尚未盘点，无法修改！");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("result", false);
            resultMap.put("msg", "系统错误！");
        }
        return resultMap;
    }

    /**
     * 盘点审核修改盘点输入栏库位（如果是已经审核成功状态的，一律无能编辑）
     * @param qaCode 质保号
     * @param shelfCode 库位完整编码
     * @param ebsCode EBS盘点单号
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/updateShelf")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateShelf(String qaCode, String shelfCode, String ebsCode) {
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            if (StringUtils.isNotBlank(shelfCode)) {
                StringBuffer inventoryIdbuffer = new StringBuffer();
                inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE", ebsCode)).forEach(inventory -> inventoryIdbuffer.append(inventory.getId()).append(","));
                List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                        .eq("QACODE", qaCode)
                        .in("PLAN_ID", inventoryIdbuffer.toString().split(",")));
                if (lstInventoryRegistration.size()>0){
                    InventoryRegistration inventoryRegistration = lstInventoryRegistration.get(0);
                    //如果已经审核成功了，那么就不能再次审核了
                    if (inventoryRegistration.getShelfState() == 1 || inventoryRegistration.getShelfState() == 2){
                        resultMap.put("result", false);
                        resultMap.put("msg", "库位审核已成功，无需修改！");
                    }else {
                        inventoryRegistration.setEditshelf(shelfCode);
                        //库存库位
                        Shelf storageShelf = shelfService.selectOne(new EntityWrapper<Shelf>()
                                .eq("FACTORYCODE", inventoryRegistration.getOrg())
                                .eq("WAREHOUSECODE", inventoryRegistration.getWarehousecode())
                                .eq("CODE", inventoryRegistration.getShelfid()));

                        //移库待执行、无需移库状态变更
                        inventoryRegistration.setShelfState(!storageShelf.getCodeComplete().equals(shelfCode) ? 3 : 2);
                        inventoryRegistrationService.updateById(inventoryRegistration);
                        resultMap.put("result", true);
                        resultMap.put("msg", "更新成功！");
                    }
                }else {
                    resultMap.put("result", false);
                    resultMap.put("msg", "此线盘尚未盘点，无法修改！");
                }
            }else {
                resultMap.put("result", false);
                resultMap.put("msg", "不能输入空库位！");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("result", false);
            resultMap.put("msg", "系统错误！");
        }
        return resultMap;
    }

    /**
     * 上传差异库位
     * @param qaCode 质保号
     * @param ebsCode ebs盘点单号
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/toMoveShelf.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> toMoveShelf(String qaCode, String ebsCode) {
        Map<String, Object> resultMap = Maps.newHashMap();
        List<Inventory> lstInventory = inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE",ebsCode));
        //一个ebs盘点单下的所有厂区
        StringBuffer factoryStringBuffer = new StringBuffer();
        //一个ebs盘点单下的所有wms盘点单号的主键
        StringBuffer inventoryIdsStringBuffer = new StringBuffer();
        lstInventory.forEach(inventory -> {
            factoryStringBuffer.append(inventory.getFactorycode());
            inventoryIdsStringBuffer.append(inventory.getId());
        });
        //有质保号，是单条上传
        if (StringUtils.isNotBlank(qaCode)){
            //对应ebs盘点单号下的已经修改库位的库存(要上传的部分)
            List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                    .in("PLAN_ID", inventoryIdsStringBuffer.toString())
                    .eq("QACODE", qaCode));
            if (lstInventoryRegistration.size()>0){
                //调EBS移库调拨接口
                Map<String,Object> xmlMap = new HashMap<>(1);
                //实时调用移库调拨接口
                String returnInfo = wmsService.FEWMS008(xmlMap,"","");
                returnInfo = returnInfo.replace(" ", "");
                //接口执行结果
                boolean interfaceExecuteResult = returnInfo.contains("<code>0</code>") || returnInfo.contains("\"code\":0") || returnInfo.contains("S000A000");
                //接口执行失败，直接返回，不做下面的任何更新操作，因为失败后，用户还需要再次点击，成功后才能更新
                if (!interfaceExecuteResult){
                    //根据接口执行结果把实时结果（返回报文）展示到前台界面
                    resultMap.put("result", false);
                    resultMap.put("msg", "接口执行失败：" + returnInfo);
                    return resultMap;
                }else {
                    resultMap.put("result", true);
                    resultMap.put("msg", "更新成功！");
                    //把移库成功的库存修改库位
                }
            }
        }else {
            //aoe盘点
            //所有的对应ebs盘点单号下的已经盘点的库存(要上传的部分)
            List<InventoryRegistration> lstInventoryRegistration = inventoryRegistrationService.selectList(new EntityWrapper<InventoryRegistration>()
                    .in("PLAN_ID", inventoryIdsStringBuffer.toString()));
            if (lstInventoryRegistration.size()>0){
                //调用盘点审核接口，把米数同步至ebs，根据返回结果，更新成功的库存
                IdentityHashMap xmlMap = null;
                for (InventoryRegistration inventoryRegistration : lstInventoryRegistration){
                    xmlMap.put("line", new HashMap<String, Object>() {{
                        put("check_num", ebsCode);
                        put("zjdh", inventoryRegistration.getQacode());
                        put("qty", inventoryRegistration.getEditmeter());
                        put("pandian_by", inventoryRegistration.getUserCode());
                    }});
                }

                //失败的质保号
                List<String> failQacodes = wmsService.FEWMS028(xmlMap, "", "");

                InventoryRegistration inventoryRegistration = new InventoryRegistration();
                //修改审核成功的执行状态为“1成功”
                if (failQacodes!=null && failQacodes.size()>0){
                    //上传成功部分
                    inventoryRegistration.setState(1L);
                    inventoryRegistrationService.update(inventoryRegistration, new EntityWrapper<InventoryRegistration>()
                            .notIn("QACODE", failQacodes)
                            .in("PLAN_ID",inventoryIdsStringBuffer.toString()));
                    //上传失败部分
                    inventoryRegistration.setState(0L);
                    inventoryRegistrationService.update(inventoryRegistration, new EntityWrapper<InventoryRegistration>()
                            .in("QACODE", failQacodes)
                            .in("PLAN_ID",inventoryIdsStringBuffer.toString()));

                    //把审核成功的库存修改数量
                    storageInfoService.updateMeterByInventory(Arrays.asList(inventoryIdsStringBuffer.toString().split(",")), failQacodes);
                }else {
                    //全部上传成功
                    inventoryRegistration.setState(1L);
                    inventoryRegistrationService.update(inventoryRegistration, new EntityWrapper<InventoryRegistration>()
                            .in("PLAN_ID",inventoryIdsStringBuffer.toString()));
                }
            }
        }

        //更新计划单状态为已审核/审核中
        lstInventory.forEach(inventory -> {
            String examinedsArray = inventoryRegistrationService.selectExamineArray(inventory.getId().intValue());
            inventoryRegistrationService.updateExamStatus(inventory.getId().intValue(), StringUtils.isBlank(examinedsArray)|| examinedsArray.contains("0") ? 1L : 2L);
        });

        return new HashMap<String,Object>(2) {{
            put("result",true);
            put("msg","审核成功！");
        }};
    }

    /**
     * 变更审核日期
     * @param date 审核日期
     * @param ebsCode  ebs盘点单号
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/confirmAuditDate.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> confirmAuditDate(String date, String ebsCode){
        inventoryService.confirmAuditTime(ebsCode, DateUtils.stringToDate(date, Constant.sdfTime));
        return new HashMap<String, Object>(2){{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

}
